package com.example.testluckyroulette.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.view.marginRight
import com.example.testluckyroulette.R
import kotlin.math.log

/**
 * Create Time:2020/9/7
 * Author: Lindanrong
 * Description:一个幸运的轮盘
 * 本控件的责任 ：画一个在中心点
 */
class LuckyRouletteView : View{

    companion object {
        private const val TAG = "LuckyRouletteView"
    }
    var mBackRoundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) //背景圆盘

    var mRadio:Int = 500 //圆盘的半径
    var mRect:RectF = RectF()//圆盘的矩形
    var mCenterBitmapRect:RectF = RectF()//中心的图像的大小
    var mHeight:Int = 0 //记录本控件的高
    var mWith:Int = 0 //记录本控件的宽
    var bitmap:Bitmap? = null // bitmap
    var mContext:Context
    constructor(context: Context):this(context,null)

    constructor(context: Context,attributeSet: AttributeSet?):this(context,attributeSet,0)

    constructor(context: Context,attributeSet: AttributeSet?,defStyleAttr:Int): super(context,attributeSet,defStyleAttr){
        mContext = context
        init()
    }

    private fun init() {
        mBackRoundPaint.style = Paint.Style.FILL
        bitmap = BitmapFactory.decodeResource(mContext.resources,R.mipmap.ic_luckdrawstart) //中心的图像
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        Log.d(TAG, "onMeasure: 宽：${MeasureSpec.getSize(widthMeasureSpec)},高：${MeasureSpec.getSize(heightMeasureSpec)}")
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

    }

    /**
     * 用于获取控件的宽高
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        Log.d(TAG, "onSizeChanged: 宽:${w}高:${h}")
        mHeight = h
        mWith = w
        mRadio = if (w>h){
            h/2
        }else{
            w/2
        }
        //确定一下圆心的坐标
        mRect.run {
            top = 0f
            left = 0f
            right = mRadio * 2f
            bottom = mRadio * 2f
        }
        // 半径 1/4 的宽高
        mCenterBitmapRect.run {
            top = mRadio - 0.25f * mRadio
            left = mRadio - 0.25f * mRadio
            right = mRadio + 0.25f * mRadio
            bottom = mRadio + 0.25f * mRadio
        }

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawBitmap(bitmap!!,null,mCenterBitmapRect,mBackRoundPaint)
    }

}